<template>
  <div id="echart" ref="chartRef" @mouseover="handleMouseOver" @mouseout="handleMouseOut"></div>
</template>

<script setup>
import { ref, reactive, watch, onUnmounted, nextTick, markRaw, toRefs, onMounted } from 'vue'
import * as charts from 'echarts'

const props = defineProps({
  option: {
    type: Object,
    require: true
  },

  isFirst: {
    type: Boolean,
    default: false
  },

  container: {
    type: String,
    default: 'container'
  }
})

const { option } = toRefs(props)

const chartRef = ref()
const Aecharts = reactive({ value: '' })

const changeEcharts = (option) => {
  Aecharts.value.setOption(option)
  if (props.isFirst) {
    let index = 0
    Aecharts.value.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: 0
    })
    Aecharts.value.on('mouseover', (e) => {
      if (e.dataIndex !== index) {
        Aecharts.value.dispatchAction({
          type: 'downplay',
          seriesIndex: 0,
          dataIndex: index
        })
      } else {
        Aecharts.value.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: e.dataIndex
        })
      }
    })
    Aecharts.value.on('mouseout', (e) => {
      index = e.dataIndex
      Aecharts.value.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex: e.dataIndex
      })
    })
  }
}

const Cancel = ref(null)

const startAutoplay = () => {
  let currentIndex = -1
  let option = props.option
  Cancel.value = setInterval(() => {
    let dataLen = option.series[0].data.length
    Aecharts.value.dispatchAction({
      type: 'downplay',
      seriesIndex: 0,
      dataIndex: currentIndex
    })
    currentIndex = (currentIndex + 1) % dataLen
    Aecharts.value.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: currentIndex
    })
    Aecharts.value.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: currentIndex,
      // 传递额外参数，确保 tooltip 的 formatter 能正确获取数据
      position: [option.series[0].data[currentIndex].x, option.series[0].data[currentIndex].y],
      name: option.series[0].data[currentIndex].name,
      value: option.series[0].data[currentIndex].value
    })
  }, 1000)
}

const Autoplay = () => {
  startAutoplay()
}

const handleMouseOver = () => {
  if (Cancel.value) {
    clearInterval(Cancel.value)
    Cancel.value = null
  }
}

const handleMouseOut = () => {
  if (!Cancel.value) {
    startAutoplay()
  }
}

watch(
  option,
  (newval) => {
    nextTick(() => {
      changeEcharts(newval)

      Aecharts.value.resize()
    })
  },
  { deep: true, immediate: true }
)

onMounted(() => {
  Aecharts.value = markRaw(charts.init(chartRef.value))
  Autoplay()
})

onUnmounted(() => {
  clearInterval(Cancel.value)
})
</script>

<style lang="scss" scoped>
#echart {
  width: 100%;
  height: 100%;
}
</style>
